package com.common.www.controller.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import org.springframework.boot.base.jpa.service.IBaseService;
import org.springframework.boot.base.jpa.domain.PageableRequest;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.Sort;
import com.common.www.utils.R;
import com.common.www.utils.TxtUtil;

import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: bianmaba-web-framework-extends
 * @description:
 * @author: Chenjiabin
 * @create: 2018-04-23 20:05
 **/
public abstract class DefaultReadController<T, ID extends Serializable> {


    protected IBaseService<T, ID> getService() {
        return null;
    }

    @ApiOperation(value = "根据数据ID查询单个数据", notes = "如果指定ID的数据不存在，则返回NULL")
    @ApiImplicitParam(name = "id", value = "查询", dataType = "int", paramType = "query")
    @RequestMapping(value = "/getById", method = RequestMethod.POST)
    public Result<T> getById(ID id) {
        return R.ok(getService().findOne(id));
    }

    @ApiOperation(value = "获取所有数据", notes = "返回数据中的data为一个数据列表")
    @RequestMapping(value = "/all", method = RequestMethod.POST)
    public Result<List<T>> all() {
        return R.ok(getService().all());
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", value = "params", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageable", value = "pageable", dataType = "string", paramType = "query"),
    })
    @ApiOperation(value = "综合查询接口", notes = "返回数据中的data为一个数据列表<br/>此函数有2组参数，第一组是查询参数，以params开头，第二组为分页参数，以pageable开头<br/>参数示例如下（支持form data或queryString），<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;params.username_eq:maomao(表示username等于maomao,eq表示等于)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;params.age_gt:10(表示age大于10，gt表示大于，ge为大于等于，le为小于等于，lt为小于)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;params.xxx_like:val%(表示用某个属性做LIKE比较,比较值为val%，另外支持notlike)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.page:0(当前页)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.start:0(起始记录)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.size:25(共取多少条数据)<br/>\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.sort:【{\"property\":\"cdt\",\"direction\":\"ASC\"}】(用cdt降序排序，支持多组排序)")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public Result<List<T>> query(String params, Integer page, Integer size, String sortJsonStr) {
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }
        LinkedHashMap<String, Object> hashMap = (LinkedHashMap<String, Object>)
                JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
                });
        if (hashMap == null)
            hashMap = new LinkedHashMap<>();
        //去掉空值的数据
        for (int i = 0; i < hashMap.size(); i++) {
            if (TxtUtil.isEmpty(hashMap.values().toArray()[i] + "")) {
                hashMap.remove(hashMap.keySet().toArray()[i]);
                i--;
                continue;
            }
            if (hashMap.values().toArray()[i] instanceof JSONArray) {//如果是in语句则转换一下
                JSONArray array = (JSONArray) hashMap.values().toArray()[i];
                Object[] objects = new Object[array.size()];
                for (int j = 0; j < array.size(); j++) {
                    objects[j] = array.get(j);
                }
                hashMap.put(hashMap.keySet().toArray()[i].toString(), objects);
            }
        }

        PageableRequest pageableRequest = new PageableRequest();
        pageableRequest.setPage(page - 1);
        pageableRequest.setSize(size);
        if (!TxtUtil.isEmpty(sortJsonStr)) {
            List<Sort> sortList = JSON.parseArray(sortJsonStr, Sort.class);
            if (sortList != null) {
                pageableRequest.setSort(JSON.toJSONString(sortList));
            }
        }

        Page<T> pageRes = getService().query(hashMap, pageableRequest);
        return R.ok(pageRes);
    }

//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "params", value = "params", dataType = "string", paramType = "query"),
//            @ApiImplicitParam(name = "pageable", value = "pageable", dataType = "string", paramType = "query"),
//    })
//    @ApiOperation(value = "综合查询接口", notes = "返回数据中的data为一个数据列表<br/>此函数有2组参数，第一组是查询参数，以params开头，第二组为分页参数，以pageable开头<br/>参数示例如下（支持form data或queryString），<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.username_eq:maomao(表示username等于maomao,eq表示等于)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.age_gt:10(表示age大于10，gt表示大于，ge为大于等于，le为小于等于，lt为小于)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.xxx_like:val%(表示用某个属性做LIKE比较,比较值为val%，另外支持notlike)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.page:0(当前页)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.start:0(起始记录)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.size:25(共取多少条数据)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.sort:【{\"property\":\"cdt\",\"direction\":\"ASC\"}】(用cdt降序排序，支持多组排序)")
//    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
//    public Result<List<T>> queryPage(PageableRequest pageable, String params) {
//        if (pageable.getPageNumber() > 0) {
//            pageable.setPage(pageable.getPageNumber() - 1);
//        }
//
//        //将params转化为map对象，并去掉空值的数据
//        LinkedHashMap<String, Object> queryParams = new LinkedHashMap<>();
//        if (StringUtils.isNotBlank(params)) {
//            LinkedHashMap<String, Object> hashMap = JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
//            });
//            for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
//                if (entry.getValue() != null) {
//                    if (entry.getValue() instanceof String && StringUtils.isNotBlank((String) entry.getValue())) {
//                        queryParams.put(entry.getKey(), entry.getValue());
//                    } else if (!(entry.getValue() instanceof String)) {
//                        queryParams.put(entry.getKey(), entry.getValue());
//                    }
//                }
//            }
//        }
//
//        Page<T> page = getService().query(queryParams, pageable);
//        return ResultUtil.ok(page);
//    }

//    @ApiOperation(value = "去重复的综合查询接口", notes = "返回数据中的data为一个数据列表<br/>此函数有2组参数，第一组是查询参数，以params开头，第二组为分页参数，以pageable开头<br/>参数示例如下（支持form data或queryString），<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.username_eq:maomao(表示username等于maomao,eq表示等于)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.age_gt:10(表示age大于10，gt表示大于，ge为大于等于，le为小于等于，lt为小于)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.xxx_like:val%(表示用某个属性做LIKE比较,比较值为val%，另外支持notlike)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.page:0(当前页)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.start:0(起始记录)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.size:25(共取多少条数据)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.sort:【{\"property\":\"cdt\",\"direction\":\"ASC\"}】(用cdt降序排序，支持多组排序)")
//    @RequestMapping(value = "/query_distinct_json", method = RequestMethod.POST)
//    public Result<List<T>> queryDistinctByJson(String params, String pageable) {
//        LinkedHashMap<String, Object> hashMap = (LinkedHashMap<String, Object>)
//                JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
//                });
//        PageableRequest pageableRequest = JSON.parseObject(pageable, PageableRequest.class);
//        return queryDistinct(hashMap, pageableRequest);
//    }
//
//    @ApiOperation(value = "去重复的综合查询接口", notes = "返回数据中的data为一个数据列表<br/>此函数有2组参数，第一组是查询参数，以params开头，第二组为分页参数，以pageable开头<br/>参数示例如下（支持form data或queryString），<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.username_eq:maomao(表示username等于maomao,eq表示等于)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.age_gt:10(表示age大于10，gt表示大于，ge为大于等于，le为小于等于，lt为小于)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;params.xxx_like:val%(表示用某个属性做LIKE比较,比较值为val%，另外支持notlike)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.page:0(当前页)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.start:0(起始记录)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.size:25(共取多少条数据)<br/>\n" +
//            "&nbsp;&nbsp;&nbsp;&nbsp;pageable.sort:【{\"property\":\"cdt\",\"direction\":\"ASC\"}】(用cdt降序排序，支持多组排序)")
//    @RequestMapping(value = "/query_distinct", method = RequestMethod.POST)
//    public Result<List<T>> queryDistinct(LinkedHashMap<String, Object> hashMap, PageableRequest pageableRequest) {
//        Page<T> page = getService().queryDistinct(hashMap, pageableRequest);
//        return ResultUtil.ok(page);
//    }
}
